const open = require("open");
const path = require('path');
const express = require('express')
const bodyParser = require('body-parser')

const app = express()

const basePath = __dirname.replace('\examples', '');

app.use(express.static(basePath, {
    setHeaders(res) {
        debugger
        res.cookie('XSRF-TOKEN-D', '1234abc')
    }
}))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))


const router = express.Router()

registerBaseRouter()

registerErrorRouter()

registerCancelRouter()

registerMoreRouter()

app.use(router)

module.exports = app.listen(5555, () => {
    open("http://localhost:5555/examples");
})

function registerBaseRouter() {
    router.get('/base/get', function (req, res) {
        res.json(req.query)
    })

    router.post('/base/post', function (req, res) {
        res.json(req.body)
    })

    router.post('/base/buffer', function (req, res) {
        let msg = []
        req.on('data', (chunk) => {
            if (chunk) {
                msg.push(chunk)
            }
        })
        req.on('end', () => {
            let buf = Buffer.concat(msg)
            res.json(buf.toJSON())
        })
    })
}

function registerErrorRouter() {
    router.get('/error/get', function (req, res) {
        res.status(500)
        res.end()
    })

    router.get('/error/timeout', function (req, res) {
        setTimeout(() => {
            res.json({
                msg: `hello world`
            })
        }, 3000)
    })
}

function registerCancelRouter() {
    router.get('/cancel/get', function (req, res) {
        setTimeout(() => {
            res.json('hello')
        }, 1000)
    })

    router.post('/cancel/post', function (req, res) {
        setTimeout(() => {
            res.json(req.body)
        }, 1000)
    })
}

function registerMoreRouter() {
    router.get('/more/get', function (req, res) {
        res.json(req.cookies)
    })

    router.post('/more/upload', function (req, res) {
        console.log(req.body, req.files)
        res.end('upload success!')
    })

    router.post('/more/post', function (req, res) {
        const auth = req.headers.authorization
        const [type, credentials] = auth.split(' ')
        console.log(atob(credentials))
        const [username, password] = atob(credentials).split(':')
        if (type === 'Basic' && username === 'Yee' && password === '123456') {
            res.json(req.body)
        } else {
            res.status(401)
            res.end('UnAuthorization')
        }
    })

    router.get('/more/304', function (req, res) {
        res.status(304)
        res.end()
    })

    router.get('/more/A', function (req, res) {
        res.end('A')
    })

    router.get('/more/B', function (req, res) {
        res.end('B')
    })
}
